#coding=utf-8
from uliweb.form import *
from uliweb.i18n import ugettext_lazy as _

class PlanEditForm(Form):
    def form_validate(self, data):
        from uliweb.orm import get_model
        
        error = {}
        
        b = data.get('begin_date')
        e = data.get('end_date')
        if not b:
            error['begin_date'] = '计划开始时间不能为空'
        if not e:
            error['end_date'] = '计划结束时间不能为空'
        if b and (b < self.task.begin_time or b > self.task.end_time):
            error['begin_date'] = '计划开始时间必须在任务周期(%s-%s)之内' % (self.task.begin_time, self.task.end_time)
        if e and (e < self.task.begin_time or e > self.task.end_time):
            error['end_date'] = '计划结束时间必须在任务周期(%s-%s)之内' % (self.task.begin_time, self.task.end_time)
        if error:
            return error
        
        if e<b:
            error['end_date'] = '计划结束时间不能小于计划开始时间'
           
        Plan = get_model('plan')
        PlanEdit = get_model('planedit')
        s_ids = self.object.systems.ids()
        plan = Plan.get((Plan.c.idn==self.object.idn) & (Plan.c.task==self.object._task_))
        if plan:
            if not data.get('enabled', False):
                systems = self._check_plan_modified(plan)
                if systems:
                    error['enabled'] = '不能禁止，存在已经开始执行计划系统'
                        
            systems_diff = set(s_ids) - set(data.get('systems', []))
            if systems_diff:
                systems = self._check_plan_modified(plan, systems_diff)
                if systems:
                    error['systems'] = '不能删除，存在已经开始执行计划系统'
        
        #检查如果是主计划,是否有选择的系统存在对应的idn的子计划,如果有,则报错
        if self.object.is_reserved and self.object.is_public:
            sys_diff = set(data.get('systems', [])) - set(s_ids)
            if sys_diff:
                c_ids = self.object.task.child_tasks.ids()
                count = 0
                sys_ = []
                tasks_ = []
                for row in Plan.filter(Plan.c.task.in_(c_ids)).filter(Plan.c.idn==self.object.idn).filter(Plan.c.main_sys.in_(sys_diff)).all():
                    count += 1
                    sys_.append(row.main_sys.abbr)
                    tasks_.append(row._task_)
                if count>0:
                    error['systems'] = u'存在以下系统:%s, 已经创建该私有计划,需要先将相关系统此计划删除' % ','.join(sys_)
                else:
                    #删除PlanEdit中已经存在的idn记录
                    PlanEdit.filter(PlanEdit.c.task.in_(tasks_)).filter(PlanEdit.c.idn==self.object.idn).filter(PlanEdit.c.main_sys.in_(sys_diff)).remove()
            
        #如果是公共，则必须选择系统
        if data.get('is_public') and not data.get('systems'):
            error['systems'] = '当阶段为公共时，关联系统不能为空'
            
        return error

class MilestoneEditForm(Form):
    def form_validate(self, data):
        from uliweb.orm import get_model
        error = {}
        
        e = data.get('end_date')
        if not e:
            error['end_date'] = '计划结束时间不能为空'
        if e and (e < self.task.begin_time or e > self.task.end_time):
            error['end_date'] = '计划结束时间必须在任务周期(%s-%s)之内' % (self.task.begin_time, self.task.end_time)
        if error:
            return error
        
        Plan = get_model('plan')
        PlanEdit = get_model('planedit')
        s_ids = self.object.systems.ids()
        plan = Plan.get((Plan.c.idn==self.object.idn) & (Plan.c.task==self.object._task_))
        if plan:
            if not data.get('enabled', False):
                systems = self._check_plan_modified(plan)
                if systems:
                    error['enabled'] = '不能禁止，存在已经开始执行计划系统'
                        
            systems_diff = set(s_ids) - set(data.get('systems', []))
            if systems_diff:
                systems = self._check_plan_modified(plan, systems_diff)
                if systems:
                    error['systems'] = '不能删除，存在已经开始执行计划系统'

        #检查如果是主计划,是否有选择的系统存在对应的idn的子计划,如果有,则报错
        if self.object.is_reserved and self.object.is_public:
            sys_diff = set(data.get('systems', [])) - set(s_ids)
            if sys_diff:
                c_ids = self.object.task.child_tasks.ids()
                count = 0
                sys_ = []
                tasks_ = []
                for row in Plan.filter(Plan.c.task.in_(c_ids)).filter(Plan.c.idn==self.object.idn).filter(Plan.c.main_sys.in_(sys_diff)).all():
                    count += 1
                    sys_.append(row.main_sys.abbr)
                    tasks_.append(row._task_)
                if count>0:
                    error['systems'] = u'存在以下系统:%s, 已经创建该私有计划,需要先将相关系统此计划删除' % ','.join(sys_)
                else:
                    #删除PlanEdit中已经存在的idn记录
                    PlanEdit.filter(PlanEdit.c.task.in_(tasks_)).filter(PlanEdit.c.idn==self.object.idn).filter(PlanEdit.c.main_sys.in_(sys_diff)).remove()

        #如果是公共，则必须选择系统
        if data.get('is_public') and not data.get('systems'):
            error['systems'] = '当里程碑为公共时，关联系统不能为空'
           
        return error

class PlanAddForm(Form):
    def form_validate(self, data):
        error = {}
        
        b = data.get('begin_date')
        e = data.get('end_date')
        if not b and data.get('type') == '1':
            error['begin_date'] = '计划开始时间不能为空'
        if not e:
            error['end_date'] = '计划结束时间不能为空'
        if b and (b < self.task.begin_time or b > self.task.end_time):
            error['begin_date'] = '计划开始时间必须在任务周期(%s-%s)之内' % (self.task.begin_time, self.task.end_time)
        if e and (e < self.task.begin_time or e > self.task.end_time):
            error['end_date'] = '计划结束时间必须在任务周期(%s-%s)之内' % (self.task.begin_time, self.task.end_time)
        if error:
            return error
        
        if data.get('type') == '1' and e<b:
            error['end_date'] = '计划结束时间不能小于计划开始时间'
            
        #如果是公共，则必须选择系统
        if data.get('is_public') and not data.get('systems'):
            error['systems'] = '当计划为公共时，关联系统不能为空'
           
        return error

class AddWorkForm(Form):
    def form_validate(self, data):
        from datetime import date
        from uliweb import settings
        error = {}
        
        now = date.today()
        
        b = data.get('begin_time')
        e = data.get('end_time')
        
        y1 = b.year, b.month
        y2 = e.year, e.month
        if y1 != y2:
            error['end_time'] = '结束日期需要与开始日期为相同的年/月'
        
        if e<b:
            error['end_time'] = '报工结束时间不能小于报工开始时间'
        
        if e > now:
            error['end_time'] = '报工结束时间不能大于当天'
            
#        if self.plan.task.stage == '00':
#            error['amount_inner_input'] = '任务尚未开始，不能报工'
        
        if self.pe.task.task_type in settings.get_var('PARA/TASK_TYPE_JUDGE_ASSIGNMENT', []) and not self.pe.task.assignment:
            error['amount_inner_input'] = '任务书不能为空，请先补录任务书'
            
        fs = ['amount_inner_input', 'amount_outer_input', 
            'amount_inner_design', 'amount_outer_design', 'amount_inner_out8', 
            'amount_outer_out8', 'amount_inner_weekend', 'amount_outer_weekend']
        t = 0
        for f in fs:
            t += data.get(f, 0)
        if t == 0:
            error['amount_inner_input'] = '工作量合计不能为0'
            
#        if b < self.plan.begin_date or b > self.plan.end_date:
#            error['begin_time'] = '报工开始时间不在阶段的计划时间范围内'
#            
#        if e < self.plan.begin_date or e > self.plan.end_date:
#            error['end_time'] = '报工结束时间不在阶段的计划时间范围内'
        return error
    
class PlanExecuteEditForm(Form):
    def form_validate(self, data):
        from datetime import date, timedelta
        from uliweb import settings
        from uliweb.orm import get_model
        from sqlalchemy.sql import and_, or_
        
        error = {}
        
        now = date.today()
        
        if self.object.type == '1':
            b = data.get('finish_begin_date')
        else:
            b = None
        e = data.get('finish_end_date')
        
        if b and e and e<b:
            error['finish_end_date'] = '阶段结束时间不能小于阶段开始时间'
        
        d = now + timedelta(days=settings.get_var("PARA/PLAN_PRE"))
        if e and e > d:
            error['finish_end_date'] = '阶段结束时间不能大于%s' % d
        if b and b > now:
            error['finish_begin_date'] = '阶段开始时间不能大于今天'
        
        #如果是结束时间，并且设置时间不为空，则检查是否还有没完成的计划项
        if self.object.plan.idn == '1090' and data.get('finish_end_date'):
            PlanExecute = get_model('planexecute')
            condition = (PlanExecute.c.id!=self.object.id) & (PlanExecute.c.task==self.object._task_)
            condition = and_(condition,
                or_(((PlanExecute.c.type=='1') & ((PlanExecute.c.finish_begin_date==None) | (PlanExecute.c.finish_end_date==None))),
                    ((PlanExecute.c.type=='2') & (PlanExecute.c.finish_end_date==None))
                    ))
            count = PlanExecute.count(condition)
            if count > 0:
                error['finish_end_date'] = '还有没有处理完毕的里程碑或阶段，请先设置其完成时间' 
                
        
#        if b:
#            if b and (b < self.object.plan.begin_date or b > self.object.plan.end_date):
#                error['finish_begin_date'] = '报工开始时间不在阶段的计划时间范围内'
#                
#            if e < self.object.plan.begin_date or e > self.object.plan.end_date:
#                error['finish_end_date'] = '报工结束时间不在阶段的计划时间范围内'
        
        return error
    
class PlanExecuteDetailsForm(Form):
    def form_validate(self, data):
        error = {}
        
        if data['finish']<0.0 or data['finish'] > 1.0:
            error['finish'] = '实际完成进度需要是0-1之间的数值'
            
        return error
